#include "StaffListDialog.h"
#include "ui_StaffListDialog.h"
#include <QDate>
#include <QMessageBox>
#include <QMenu>
#include "degelate.h"
#include "present/Printer.h"
#include "present/ExportExcel.h"
#include "buttondelegate.h"
#include "checkboxheaderview.h"


/*
 * 函数名：StaffListDialog
 * 函数说明:构造函数
 *
 *
 * 输入参数：parent： 父类指针
 * 输出参数：无
 * 返回值：无
 * */
StaffListDialog::StaffListDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::StaffListDialog),
    m_pageCount(2000)
{
    ui->setupUi(this);


    ui->tableWidget->setMouseTracking(true);//鼠标追踪启用 则可以触发hover事件

//    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
//    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
//    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableWidget->setAlternatingRowColors(true);
    ui->tableWidget->setColumnCount(5);


//    if (m_checkboxDelegate){
//        delete m_checkboxDelegate;
//    }
    m_isAllCheck = false;
    m_checkboxDelegate = new CheckboxDelegate(ui->tableWidget);
    m_checkboxDelegate->setAllChecked(ui->tableWidget->rowCount(),true);
    ui->tableWidget->setItemDelegateForColumn(0,m_checkboxDelegate);
    ui->tableWidget->setItemDelegateForColumn(1,new ReadOnlyDelegate(ui->tableWidget));//设置id列为只读
    ui->tableWidget->setItemDelegateForColumn(3,new SexDelegate(ui->tableWidget) );//设置性别下拉框
    ui->tableWidget->setItemDelegateForColumn(4,new ButtonDelegate(ui->tableWidget));//设置按钮

   CheckBoxHeaderView *myHeader = new CheckBoxHeaderView(Qt::Horizontal,ui->tableWidget);
   ui->tableWidget->setHorizontalHeader(myHeader);
//   myHeader->setSortIndicator(0,Qt::AscendingOrder);
//   myHeader->setSortIndicatorShown(true);
   myHeader->setSectionsClickable(true);
   connect(myHeader,SIGNAL(sectionClicked(int)),this,SLOT(on_checkAll_clicked(int)));

    this->initActions();


    connect(ui->comboBox_dep,SIGNAL(currentIndexChanged(int)),this,SLOT(loadMajorByDep()));

    connect(ui->comboBox_major,SIGNAL(currentIndexChanged(int)),this,SLOT(loadClassByMajorAndGrade()));



    //加载部门信息　后续信息会自动加载
    this->loadDeps();


    ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);

    connect(ui->tableWidget,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(onMenu(QPoint)));

    connect(ui->tableWidget,SIGNAL(itemChanged(QTableWidgetItem*)),this,SLOT(onItemChanged(QTableWidgetItem*)));

    connect(ui->tableWidget->horizontalHeader(),SIGNAL(sectionClicked(int)),this,SLOT(sortByColumn(int)));

    ui->comboBox->addItems(QStringList()<<"工号"<<"员工姓名"<<"性别");
    connect(ui->comboBox,SIGNAL(selectionChanged(QString)),this,SLOT(columnVisibleChange(QString)));

}


/*
 * 函数名：~StaffListDialog
 * 函数说明:析构函数
 *
 *
 * 输入参数：无
 * 输出参数：无
 * 返回值：无
 * */
StaffListDialog::~StaffListDialog()
{
    delete ui;
}



/*
 * 函数名：initActions
 * 函数说明:初始化
 *
 *
 * 输入参数：无
 * 输出参数：无
 * 返回值：无
 * */
void StaffListDialog::initActions()
{
    m_actionAdd = new QAction("新建员工",this);

    m_actionDel = new QAction("删除员工",this);

    connect(m_actionAdd,SIGNAL(triggered(bool)),this,SLOT(onAddStaff()));

    connect(m_actionDel,SIGNAL(triggered(bool)),this,SLOT(onDelStaff()));

}


/*
 * 函数名：queryCount
 * 函数说明:查询员工总数量数量
 *
 *
 * 输入参数：无
 * 输出参数：无
 * 返回值：无
 * */
void StaffListDialog::queryCount()
{
    int totalCount=0;

    //如果数据量大于0 设置spinbox页数
    if (totalCount>0){
        qDebug()<<"totalCount"<<totalCount<<qCeil(totalCount/(m_pageCount*1.0));
        m_totalPage=qCeil(totalCount/(m_pageCount*1.0));
        ui->spinBox->setValue(1);
        ui->spinBox->setMinimum(1);
        ui->spinBox->setMaximum(qCeil(totalCount/(m_pageCount*1.0)));
        ui->lbl_totalPage->setText(QString::number(qCeil(totalCount/(m_pageCount*1.0))));
        qDebug()<<"spinBox"<<ui->spinBox->minimum()<<ui->spinBox->maximum();
    }else{
        m_totalPage=0;
    }
}

/*
 * 函数名：refresh
 * 函数说明:刷新下拉列表
 *
 *
 * 输入参数：无
 * 输出参数：无
 * 返回值：无
 * */
void StaffListDialog::refresh()
{
    loadDeps();

}

/*
 * 函数名：loadDeps
 * 函数说明:加载部门数据
 *
 *
 * 输入参数：无
 * 输出参数：无
 * 返回值：无
 * */
void StaffListDialog::loadDeps()
{
    QList<DepartmentInfo> deps = m_departmentDao.departmentList();

    ui->comboBox_dep->clear();

    for(DepartmentInfo & info : deps)
    {
        ui->comboBox_dep->addItem(info.dep_name,info.dep_id);
    }
}


/*
 * 函数名：loadMajorByDep
 * 函数说明:通过部门加载小组数据
 *
 *
 * 输入参数：无
 * 输出参数：无
 * 返回值：无
 * */
void StaffListDialog::loadMajorByDep()
{
    ui->comboBox_major->clear();

    int dep_id = ui->comboBox_dep->currentData().toInt();


    QList<GroupInfo> groups = m_groupDao.groupList(dep_id);


    for(GroupInfo & info : groups)
    {
         ui->comboBox_major->addItem(info.group_name,info.group_id);
    }
}


/*
 * 函数名：loadClassByMajorAndGrade
 * 函数说明：通过部门和小组信息加载员工信息
 *
 *
 * 输入参数：无
 * 输出参数：无
 * 返回值：无
 * */
void StaffListDialog::loadClassByMajorAndGrade()
{
    int group_id = ui->comboBox_major->currentData().toInt();



    QList<StaffInfo> stuInfos = m_StaffService.staffList(group_id);


    m_isLoading = true;

    ui->tableWidget->clear();


    ui->tableWidget->setRowCount(stuInfos.size());

    ui->tableWidget->setHorizontalHeaderLabels(QStringList()<<""<<"工号"<<"员工姓名"<<"性别");


    for(int i = 0 ;i < stuInfos.size();i++)
    {

        StaffInfo & info = stuInfos[i];

        QTableWidgetItem * name_item = new QTableWidgetItem(info.staff_name);
//        name_item->setTextAlignment(Qt::AlignCenter);
//        name_item->setData(Qt::UserRole,info.staff_idcard);

        QTableWidgetItem * idcard_item = new QTableWidgetItem(QString::number(info.staff_idcard));
//        idcard_item->setTextAlignment(Qt::AlignCenter);

        QTableWidgetItem * sex_item = new QTableWidgetItem(info.staff_sex==0?"男":"女");
//        sex_item->setTextAlignment(Qt::AlignCenter);


        ui->tableWidget->setItem(i,1,idcard_item);
        ui->tableWidget->setItem(i,2,name_item);
        ui->tableWidget->setItem(i,3,sex_item);
        //qDebug()<<info.staff_name<<info.staff_idcard<<info.staff_sex;


    }


    m_isLoading = false;

}



/*
 * 函数名：onMenu
 * 函数说明：槽函数 右键点击表格弹出菜单
 *
 *
 * 输入参数：无
 * 输出参数：无
 * 返回值：无
 * */
void StaffListDialog::onMenu(QPoint)
{

    QMenu menu;

    menu.addActions(QList<QAction*>()<<m_actionAdd<<m_actionDel);

    menu.exec(QCursor::pos());
}


/*
 * 函数名：onAddStaff
 * 函数说明：槽函数 添加员工
 *
 *
 * 输入参数：无
 * 输出参数：无
 * 返回值：无
 * */
void StaffListDialog::onAddStaff()
{

    m_isLoading = true;

    int index = ui->tableWidget->rowCount();


    ui->tableWidget->insertRow(index);

    QTableWidgetItem * name_item = new QTableWidgetItem();

    QTableWidgetItem * idcard_item = new QTableWidgetItem( );

    QTableWidgetItem * sex_item = new QTableWidgetItem();


    ui->tableWidget->setItem(index,1,idcard_item);
    ui->tableWidget->setItem(index,2,name_item);
    ui->tableWidget->setItem(index,3,sex_item);


    m_isLoading = false;

}


/*
 * 函数名：onDelStaff
 * 函数说明：槽函数 删除员工函数
 *
 *
 * 输入参数：无
 * 输出参数：无
 * 返回值：无
 * */
void StaffListDialog::onDelStaff()
{
    QTableWidgetItem * item = ui->tableWidget->currentItem();


    if(item)
    {
        int btn = QMessageBox::warning(this,"警告","确认删除该员工！","是","否");

        if(btn == 0)
        {
            //执行删除
            int stu_id = ui->tableWidget->item(item->row(),1)->text().toInt();

            m_StaffService.delStaff(stu_id);

            //刷新
            this->loadClassByMajorAndGrade();
        }
    }
}

/*
 * 函数名：onItemChanged
 * 函数说明：槽函数 表格数据有变化
 *
 *
 * 输入参数：item：改变的item
 * 输出参数：无
 * 返回值：无
 * */
void StaffListDialog::onItemChanged(QTableWidgetItem *  item)
{
    if(item->text() != "" && !m_isLoading)
    {

        int major_id = ui->comboBox_major->currentData().toInt();

        int stu_id = ui->tableWidget->item(item->row(),1)->text().toInt();

        QString stuName = ui->tableWidget->item(item->row(),2)->text();

        QString sex = ui->tableWidget->item(item->row(),3)->text();
        int sexInt = 0;
        if(sex=="男")
        {
           sexInt=0;
        }else{
            sexInt=1;
        }


        if(stu_id == 0)
        {



            m_StaffService.addStaff(major_id,sexInt,stuName);


            this->loadClassByMajorAndGrade();

        }else
        {

            //qDebug()<<"update";
            m_StaffService.updateStaff(major_id,stu_id,sexInt,stuName);

//            this->loadData();
        }

    }
}


/*
 * 函数名：on_pushButton_printf_clicked
 * 函数说明：槽函数 弹出打印界面
 *
 *
 * 输入参数：无
 * 输出参数：无
 * 返回值：无
 * */
void StaffListDialog::on_pushButton_printf_clicked()
{
    Printer *printf = new Printer(this);
    printf->setTableWidget(ui->tableWidget);
    printf->print();
}


/*
 * 函数名：on_pushButton_export_clicked
 * 函数说明：槽函数 导出数据到excel
 *
 *
 * 输入参数：无
 * 输出参数：无
 * 返回值：无
 * */
void StaffListDialog::on_pushButton_export_clicked()
{
    QString fileName = QFileDialog::getSaveFileName(this);

    if(fileName != ""  )
    {
        if(  !fileName.endsWith(".xls") && !fileName.endsWith(".xlsx"))
        {
            fileName.append(".xls");
        }


        ExportExcel exportExcel;

        if(exportExcel.exportStaffInfo(fileName))
        {
            QMessageBox::information(this,"提示","导出完成","确认");
        }
    }
}

/*
 * 函数名：on_pushButton_back_clicked
 * 函数功能: 上一页按钮点击槽函数
 *
 *
 * 输入参数：无
 * 输出参数：无
 * 返回值：无
 * */
void StaffListDialog::on_pushButton_back_clicked()
{
    if (ui->spinBox->minimum()>0 && ui->spinBox->value()>1){

        m_curPage--;
//        queryData(m_curPage);

    }

}

/*
 * 函数名：on_pushButton_next_clicked
 * 函数功能: 下一页按钮点击槽函数
 *
 *
 * 输入参数：无
 * 输出参数：无
 * 返回值：无
 * */
void StaffListDialog::on_pushButton_next_clicked()
{
    if (m_totalPage>0 && (m_curPage+1)<m_totalPage){
        m_curPage++;
//        queryData(m_curPage);

    }

}

/*
 * 函数名：on_pushButton_last_clicked
 * 函数功能: 最后一页按钮点击槽函数
 *
 *
 * 输入参数：无
 * 输出参数：无
 * 返回值：无
 * */
void StaffListDialog::on_pushButton_last_clicked()
{
    if (ui->spinBox->maximum()>0 && ui->spinBox->value()!=ui->spinBox->maximum()){
        m_curPage=m_totalPage-1;
//        queryData(m_curPage);

    }
}

/*
 * 函数名：on_pushButton_first_clicked
 * 函数功能: 第一页按钮点击槽函数
 *
 *
 * 输入参数：无
 * 输出参数：无
 * 返回值：无
 * */
void StaffListDialog::on_pushButton_first_clicked()
{
    if (ui->spinBox->minimum()>0 && ui->spinBox->value()!=1){
        m_curPage=0;
        //queryData(m_curPage);
        //调用封装接口
    }
}


/*
 * 函数名：on_spinBox_editingFinished
 * 函数功能: 编辑spinbox槽函数 查询相应页号的数据
 *
 *
 * 输入参数：无
 * 输出参数：无
 * 返回值：无
 * */
void StaffListDialog::on_spinBox_editingFinished()
{
    //queryData(m_curPage);
}


/*
 * 函数名：on_checkAll_clicked
 * 函数功能:点击表头复选框 全选或者全部选
 *
 *
 * 输入参数：column列号
 * 输出参数：无
 * 返回值：无
 * */
void StaffListDialog::on_checkAll_clicked(int column)
{
    if(column!=0) return;
    if(ui->tableWidget->rowCount()<=0) return;
    m_isAllCheck = !m_isAllCheck;
    m_checkboxDelegate->setAllChecked(ui->tableWidget->rowCount(),m_isAllCheck);
    ui->tableWidget->update();
}


/*
 * 函数名：sortByColumn
 * 函数功能:根据列号设置排序方式
 *
 *
 * 输入参数：Column列号
 * 输出参数：无
 * 返回值：无
 * */
void StaffListDialog::sortByColumn(int Column)
{
    //ui->tableWidget->sortItems(Column,Qt::AscendingOrder);
    switch (Column) {
    case 0:
        //根据设备名称进行排序
        if(m_orderByColumnName=="deviceData asc"){

            m_orderByColumnName = "deviceData desc";//
        }else
        {
            m_orderByColumnName = "deviceData asc";//
        }
        break;
    case 1:
        //根据报警类型进行排序
        if(m_orderByColumnName=="type asc"){

            m_orderByColumnName = "type desc";//
        }else
        {
            m_orderByColumnName = "type asc";//
        }
        break;
    case 3:
        //根据报警开始时间进行排序
        if(m_orderByColumnName=="startTime asc"){

            m_orderByColumnName = "startTime desc";//
        }else
        {
            m_orderByColumnName = "startTime asc";//
        }
        break;
    default:
        return;
    };

    //刷新表格数据
//    if(ui->radioButton->isChecked())
//    {
//       updateTableView(0);//
//    }else if(ui->radioButton_2->isChecked())//
//    {
//        updateTableView(1);//
//    }
}

/*
 * 函数名：on_tableWidget_itemSelectionChanged
 * 函数功能:槽函数 行点击事件
 *
 *
 * 输入参数：无
 * 输出参数：无
 * 返回值：无
 * */
void StaffListDialog::on_tableWidget_itemSelectionChanged()
{
    //QMessageBox::information(this,tr("提醒"),tr("行点击事件!"));
}

/*
 * 函数名：on_tableWidget_clicked
 * 函数功能:槽函数 特定单格点击事件
 *
 *
 * 输入参数：index 点击单元格索引
 * 输出参数：无
 * 返回值：无
 * */
void StaffListDialog::on_tableWidget_clicked(const QModelIndex &index)
{
    //QMessageBox::information(this,tr("提醒"),tr("特定单格点击事件!"));
}

void StaffListDialog::columnVisibleChange(QString colName)
{
    QStringList colNameList = colName.split(";");
    for(int i =0;i<ui->tableWidget->columnCount();i++)
    {
        QTableWidgetItem * item = ui->tableWidget->horizontalHeaderItem(i);
        if(item==NULL) continue;
        qDebug()<<i<<ui->tableWidget->horizontalHeaderItem(i)->text()<<colNameList<<colNameList.contains(item->text());
        if(item->text()=="")continue;

        if(colNameList.contains(item->text()))
        {
            ui->tableWidget->setColumnHidden(i,false);
        }else{
            ui->tableWidget->setColumnHidden(i,true);
        }
        qDebug()<<i<<ui->tableWidget->horizontalHeaderItem(i)->text();
//        if(colNameList.contains())
    }
//    ui->tableWidget->setColumnHidden();
}
